<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">项目名称</label>
        <el-input
          v-model="query.name"
          clearable
          placeholder="项目名称"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <template slot="right">
          <el-button class="projectBtn" @click="toUser" size="mini" type="primary">项目绑定</el-button>
        </template>
      </crudOperation>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="550px"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="95px"
        >
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="form.name" style="width: 370px" />
          </el-form-item>
          <el-form-item label="可用化学品" prop="totalIds" v-if="crud.status.add != 1">
            <el-select
              v-model="form.totalIds"
              style="width: 370px"
              clearable
              filterable
              multiple
              value-key="id"
              :remote-method="get"
              placeholder="请选择可用化学品"
              @change="selectAllItems"
            >
            <!-- 添加全选选项 -->
              <el-option :key="'selectAll'" :label="selectAllLabel" :value="selectAllValue" ></el-option>
              <el-option
                v-for="item in hazardousChemicals"
                :key="item.id"
                :label="item.typeAndName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目介绍">
            <el-input v-model="form.desc" style="width: 370px" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="crud.submitCU"
            >确认</el-button
          >
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="项目名称" />
        <!-- <el-table-column prop="creatorId" label="创建人" /> -->
        <el-table-column label="项目可用化学品">
          <template slot-scope="scope">
            {{ getReagent(scope.row.projectHazardousChemicals) }}
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="项目介绍" />
        <el-table-column
          v-if="checkPer(['admin', 'project:edit', 'project:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { changeMenus } from '@/router/changemenu.js'
import crudProject from "@/api/project";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { getHazardousChemicals } from "@/api/hazardousChemicals";

const defaultForm = {
  id: null,
  name: null,
  desc: null,
  // creatorId: null,
  // createdAt: null,
  // updatedAt: null,
  totalIds: [],
};
export default {
  name: "Project",
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: "项目",
      url: "api/project",
      idField: "id",
      sort: "id,desc",
      crudMethod: { ...crudProject },
    });
  },
  data() {
    return {
      permission: {
        add: ["admin", "project:add"],
        edit: ["admin", "project:edit"],
        del: ["admin", "project:del"],
      },
      rules: {
        name: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
        ],
        totalIds: [
          { required: true, message: '项目可用化学品不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [{ key: "name", display_name: "项目名称" }],
      hazardousChemicals: [],
      totalIds: [],
      selectAllLabel: '全选',
      selectAllValue: 'all'
    };
  },
  created() {
    this.get();
  },
  methods: {
    get() {
      getHazardousChemicals()
        .then((response) => {
          this.hazardousChemicals = response.data;
          this.hazardousChemicals.forEach((item) => {
            // item.id = { id: item.id };
            const type =  item.type == 1? '器材':item.type == 2? '标准物质' : '化学试剂'
             item.typeAndName = type + ' - ' + item.name
          });
        })
        .catch((_) => {
          console.log(response);
        });
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.totalIds = [];
    },
    getReagent(data) {
      var text = "";
      data.forEach((item) => {
        text += item.name + "、";
      });
      return text ? text.substring(0, text.length - 1) : "-";
    },
    async toUser(){
      this.$store.commit('tagsView/visitedViewsDel')
      await changeMenus(8)
      this.$router.push('/user/index')
    },
    selectAllItems() {
      if (this.form.totalIds.includes(this.selectAllValue)) {
        // 如果已经包含全选值，则取消选择所有选项
        this.form.totalIds = this.hazardousChemicals.map(item => item.id);
      }
    }
  },
};
</script>

<style scoped lang="scss">
.projectBtn {
 margin: 0 3px 10px 0;
 display: inline-block;
 vertical-align: middle;
}
</style>
